package bar.dark.lee.manager.money;

import java.math.BigDecimal;
import java.util.HashMap;

import bar.dark.lee.MainActivity;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.EditTextInputFilter;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.insert.InsertPostActivity;
import bar.dark.lee.setting.data.DataOutActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class RealMoneyActivity extends SuperActivity
{
	private TextView realMoney;
	private EditText realMoneyInput;
	private Button insertButton;
	private Button updateButton;
	
	private DBSQLite sql;
	
	private String money;
	private String realMoney2;;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.setting_realmoney_activity);
		
		setGoneTitle();
		
		realMoney = (TextView) findViewById(R.id.settingRealMoneyText);
		realMoneyInput = (EditText) findViewById(R.id.settingRealMoneyEditText);
		EditTextInputFilter.filteringMoneyEditText(realMoneyInput);
		insertButton = (Button) findViewById(R.id.settingRealMoneyButton);
		updateButton = (Button) findViewById(R.id.settingRealMoneyUpdate);
		
		sql = DBSQLite.getInstance(this);
		
		insertButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (BDUtil.getCommaDel(realMoneyInput.getText().toString()).equals("") 
						||BDUtil.getCommaDel(realMoneyInput.getText().toString()).length() < 1)
				{
					BDUtil.showToast(RealMoneyActivity.this, "금액을 입력해주세요.");
					return;
				}
				
				setInsertMoney();
				setRealMoney();
				
				BDUtil.showDialog(RealMoneyActivity.this, "현금입력", "현금 입력 완료");
			}
		});
		
		updateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (BDUtil.getCommaDel(realMoneyInput.getText().toString()).equals("") 
						|| BDUtil.getCommaDel(realMoneyInput.getText().toString()).length() < 1)
				{
					BDUtil.showToast(RealMoneyActivity.this, "금액을 입력해주세요.");
					return;
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag, 2);
			}
		});
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		// 데이터를 가져온다.
		new ShowDialog().execute(BDUtil.asyncFlag, 1);
	}
	
	/**
	 * 현금을 가져온다
	 */
	private void setRealMoney()
	{
		sql.selectMapTile(this, "SELECT money FROM real_money", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int columnIndex = c.getColumnIndex("money");
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					realMoney2 = c.getString(columnIndex);
				}
			}
		});
	}
	
	/**
	 * 현금을 입력한다.
	 */
	private void setInsertMoney()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		
		BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(realMoneyInput.getText().toString()));
		
		money = tempMoney.add(new BigDecimal(realMoney2)).toString();
		
		map.put("money", money);
		sql.update(this, "real_money", map, "", null);
		
		sql.selectMapTile(this, "SELECT money FROM total_money", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
//				int totalMoney = 0;
				BigDecimal totalMoney = BigDecimal.ZERO;
				int columnIndex = c.getColumnIndex("money");
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
//					totalMoney = totalMoney + Integer.parseInt(c.getString(columnIndex));
					totalMoney = totalMoney.add(new BigDecimal(c.getString(columnIndex)));
					c.moveToNext();
				}
				
				totalMoney = totalMoney.add(new BigDecimal(BDUtil.getCommaDel(realMoneyInput.getText().toString())));
				
				HashMap<String, String> totalMap = new HashMap<String, String>();
				totalMap.put("money", totalMoney.toString());
				sql.update(RealMoneyActivity.this, "total_money", totalMap, "", null);
			}
		});
	}
	
	/**
	 * 현금을 수정한다.
	 */
	private void setUpdateMoney()
	{
		HashMap<String, String> map = new HashMap<String, String>();

		BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(realMoneyInput.getText().toString()));
		money = tempMoney.toString();
		
		map.put("money", money);
		sql.update(this, "real_money", map, "", null);
		
		sql.selectMapTile(this, "SELECT money FROM total_money", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
//				int totalMoney = 0;
				BigDecimal totalMoney = BigDecimal.ZERO;
				int columnIndex = c.getColumnIndex("money");
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
//					totalMoney = totalMoney + Integer.parseInt(c.getString(columnIndex));
					totalMoney = totalMoney.add(new BigDecimal(c.getString(columnIndex)));
					c.moveToNext();
				}
				
//				totalMoney = totalMoney - Integer.parseInt(realMoney2);
				totalMoney = totalMoney.subtract(new BigDecimal(realMoney2));
				
				totalMoney = totalMoney.add(new BigDecimal(BDUtil.getCommaDel(realMoneyInput.getText().toString())));
				
				HashMap<String, String> totalMap = new HashMap<String, String>();
				totalMap.put("money", totalMoney.toString());
				sql.update(RealMoneyActivity.this, "total_money", totalMap, "", null);
			}
		});
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(RealMoneyActivity.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0) {
				
				if (arg0[1] == 1)
				{
					setRealMoney();
					
					return arg0[1];
				}
				else if (arg0[1] == 2)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setUpdateMoney();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					setRealMoney();
					
					return arg0[1];
				}
				
				return arg0[0];
			} else 
				return arg0[0];
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 1)
			{
				realMoney.setText(BDUtil.getWon(realMoney2) + shape);
				realMoneyInput.setText("");
				
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
			}
			else if (result == 2)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(RealMoneyActivity.this, "현금수정", "현금 수정 완료");
				new ShowDialog().execute(BDUtil.asyncFlag, 1);
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
